﻿using CommunicationTools.Helper;
using Masuit.Tools;
using Microsoft.VisualBasic;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CommunicationTools.Controls
{
    public partial class SerialDemo : UIPage
    {
        private bool _log = false;
        private string // 设置文件路径为当前目录下的LogFile.txt
        logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LogFile.txt");
        private bool _isOpen = false;
        CancellationTokenSource _cts = new CancellationTokenSource();
        bool _disposed = false;
        SerialPort serialPort = new SerialPort();

        bool _autoScroll = true;
        bool _ischeckRandom = false;

        Random rd = new Random();

        public SerialDemo()
        {
            InitializeComponent();

        }

        //控制串口设置
        private void Enable(bool flag)
        {
            serial_Box.Enabled = flag;
            baudRate_Box.Enabled = flag;
            Pariy_box.Enabled = flag;
            Stopbit_Box.Enabled = flag;
            data_box.Enabled = flag;
            uiCheckBox5.Enabled = !flag;
        }


        //初始化串口设置
        private void Form1_Load(object sender, EventArgs e)
        {
            foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//自动获取串行口名称
            {
                serial_Box.Items.Add(com);
            }
            serial_Box.SelectedIndex = 0;


            baudRate_Box.SelectedIndex = 6;
            data_box.SelectedIndex = 0;


            CheckBox_DaiLog.Checked = true;
            Recive_Radio_ASCII.Checked = true;
            Radio_Send_ASCII.Checked = true;

            Pariy_box.Items.AddRange(Enum.GetNames(typeof(Parity)));
            Pariy_box.SelectedIndex = 0;



            Stopbit_Box.Items.AddRange(Enum.GetNames(typeof(StopBits)));
            Stopbit_Box.SelectedIndex = 1;

            uiCheckBox5.Enabled = false;

            //SerialPort对象接收数据
            serialPort.DataReceived += SerialPort_DataReceived;
        }

        //serialport对象的获取值事件
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (Recive_Radio_HEX.Checked)
            {
                Encoding encode = Encoding.UTF8;
                Invoke(() =>
                {
                    LogBox.AppendText(serialPort.ReadExisting().StringToHexString(encode).FormatStringLog());

                });
               
            }
            else
            {
                Invoke(() =>
                {

                    LogBox.AppendText(serialPort.ReadExisting().FormatStringLog());
                });
               
            }

            if (_autoScroll)
            {
                Invoke(() =>
                {
                    LogBox.SelectionStart = LogBox.Text.Length;
                    LogBox.ScrollToCaret();

                });
               
            }

        }



        //打开
        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {

                if (_isOpen)
                {
                    serialPort.Close();
                    btn_Open.Text = "打开";
                    LogBox.AppendText("连接关闭".FormatStringLog());
                    Enable(true);
                    _cts?.Cancel();
                }
                else
                {

                    serialPort.PortName = serial_Box.Text;
                    serialPort.BaudRate = baudRate_Box.Text.ToInt32();
                    serialPort.DataBits = data_box.Text.ToInt32();

                    if (Enum.TryParse(Pariy_box.Text, out Parity result))
                    {

                        serialPort.Parity = result;

                    }

                    if (Enum.TryParse(Stopbit_Box.Text, out StopBits stopBits))
                    {
                        if (stopBits != StopBits.None)
                        {
                            serialPort.StopBits = stopBits;
                        }
                    }

                    serialPort?.Open();
                    btn_Open.Text = "关闭";
                    Enable(false);
                    LogBox.AppendText("连接打开".FormatStringLog());
                }





            }
            catch (Exception exception)
            {
                btn_Open.Text = "打开";
                LogBox.AppendText(exception.Message.ToString().FormatStringLog());


            }
            finally
            {
                _isOpen = !_isOpen;
            }



        }

        private void checkEditRecLog_CheckedChanged(object sender, EventArgs e)
        {
            StringExtension.CheckEditRecLog = CheckBox_DaiLog.Checked;


        }

        //发送数据
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (_isOpen)
            {


                if (Radio_Send_HEX.Checked)
                {
                    Encoding encode = Encoding.UTF8;
                    serialPort.Write(SendLogBox.Text);
                    this.Invoke(() =>
                    {
                        LogBox.AppendText(SendLogBox.Text.StringToHexString(encode).FormatStringLog());
                        if (_autoScroll)
                        {
                            LogBox.SelectionStart = LogBox.Text.Length;
                            LogBox.ScrollToCaret();
                        }
                    });

                }
                else
                {
                    serialPort.Write(SendLogBox.Text);
                    this.Invoke(() =>
                    {
                        LogBox.AppendText(SendLogBox.Text.FormatStringLog());
                        if (_autoScroll)
                        {
                            LogBox.SelectionStart = LogBox.Text.Length;
                            LogBox.ScrollToCaret();
                        }
                    });

                }

            }
        }

        private void RandmSend()
        {
            if (_isOpen)
            {
                var rdlog = rd.Next(1, 99).ToString();
                Encoding encode = Encoding.UTF8;
                try
                {
                    if (Radio_Send_HEX.Checked)
                    {


                        serialPort.Write(rdlog);
                        this.Invoke(() =>
                        {
                            LogBox.AppendText(rdlog.StringToHexString(encode).FormatStringLog());
                            if (_autoScroll)
                            {
                                LogBox.SelectionStart = LogBox.Text.Length;
                                LogBox.ScrollToCaret();
                            }
                        });

                    }
                    else
                    {
                        serialPort.Write(rdlog);
                        this.Invoke(() =>
                        {
                            LogBox.AppendText(rdlog.StringToHexString(encode).FormatStringLog());
                            if (_autoScroll)
                            {
                                LogBox.SelectionStart = LogBox.Text.Length;
                                LogBox.ScrollToCaret();
                            }
                        });
                    }
                }
                catch (Exception)
                {

                    throw;
                }


            }
        }

        //检查设备是否插入
        protected override void WndProc(ref Message msg)
        {
            //设备改变
            if (msg.Msg == 0x0219)
            {
                //串口拔出
                if (msg.WParam.ToInt32() == 0x8004)
                {
                    LogBox.AppendText("设备已经拔出".FormatStringLog());
                    serial_Box.Items.Clear();
                    foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//自动获取串行口名称
                    {
                        serial_Box.Items.Add(com);
                    }
                    serial_Box.SelectedIndex = 0;
                }
                //串口连接上
                else if (msg.WParam.ToInt32() == 0x8000)
                {
                    LogBox.AppendText("设备已经插入".FormatStringLog());
                    serial_Box.Items.Clear();
                    foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//自动获取串行口名称
                    {
                        serial_Box.Items.Add(com);
                    }
                    serial_Box.SelectedIndex = 0;
                }
            }


            base.WndProc(ref msg);
        }


        //自动发送
        private async void uiCheckBox5_CheckedChanged(object sender, EventArgs e)
        {
            _disposed = !_disposed;


            _cts = new CancellationTokenSource();





            if (_disposed)
            {
                await Task.Run(async () =>
                {


                    while (!_cts.IsCancellationRequested)
                    {
                        await Task.Delay(TimeBox.Text.ToInt32());

                        if (_ischeckRandom)
                        {
                            RandmSend();
                        }
                        else
                        {


                            btnSend_Click(sender, e);
                        }


                    }
                }, _cts.Token);
            }
            else
            {
                _cts.Cancel();
            }



        }

        //是否生成随机数
        private void CheckBox_Send_Random_CheckedChanged(object sender, EventArgs e)
        {
            _ischeckRandom = !_ischeckRandom;
        }


        //实现RichBox自动滚屏效果（LogBox）
        private void CheckBox_AutoScroll_CheckedChanged(object sender, EventArgs e)
        {
            _autoScroll = !_autoScroll;

        }

        //LogBox值改变后
        private void LogAppend()
        {
            // 确保文件操作在后台线程中进行，避免阻塞UI线程
            var logContent = LogBox.Text;
            try
            {
                using (StreamWriter writer = new StreamWriter(logFilePath))
                {
                    // 如果文件非空，则在内容前加上换行符
                    if (File.Exists(logFilePath) && new FileInfo(logFilePath).Length > 0)
                    {
                        writer.WriteLine();
                    }
                    // 写入当前LogBox的内容
                    writer.Write(logContent);
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        //轮询添加日志
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (_log)
            {
                LogAppend();
            }
            
        }

        //是否添加日志
        private void CheckBox_ReciveToFill_CheckedChanged(object sender, EventArgs e)
        {
            _log = !_log;
            if (_log)
            {
                timer1.Start();
            }
            else
            {
                timer1.Stop();
            }

        }
    }
}
